from openai import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain.agents import tool
from langchain.prompts import ChatPromptTemplate,MessagesPlaceholder
from langchain.tools.render import format_tool_to_openai_function
from langchain.agents.format_scratchpad import format_to_openai_function_messages
from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser


@tool
def get_word_length(word:str) -> int:
    """

    :param word:
    :return:
    """
    return len(word)

tools = [get_word_length]

llm = ChatOpenAI(
    model="gpt-3.5-turbo",
    temperature=0.3,
    max_tokens=200,
    api_key="hk-mtiquv1000041663a49a34520ad3294132cbce7abf1c2ef3",
    base_url="https://api.openai-hk.com/v1"
)

prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are very powerful assistant,but had at calculation lengths of words."
        ),
        (
            "user","{input}"
        ),
        MessagesPlaceholder(variable_name='agent_scratchpad')
    ]
)
llm_with_tools = llm.bind(functions=[format_tool_to_openai_function(t) for t in tools])

agent = (
    {
        "input":lambda x:x["input"],
        "agent_scratchpad": lambda x:format_tool_to_openai_function(x["intermediate_steps"]),
    }
    |prompt
    |llm_with_tools
    |OpenAIFunctionsAgentOutputParser
)

agent.invoke({"input":"how many letters in the word educa?","intermediate_steps":[]})